//
//  HLStatusesViewModel.swift
//  HLwWeibo
//
//  Created by hqhxu on 16/3/2.
//  Copyright © 2016年 hqhxu. All rights reserved.
//

import UIKit

import SDWebImage

class HLStatusesViewModel: NSObject {

    /// 单例 微博处理类
    static let shareInstance = HLStatusesViewModel()
    
    
    /// 加载微博数据
    func loadStatuses(since_id:Int?, max_id:Int?,finshesCallBack:(statuses:[HLStatuses]?,error:NSError?) ->()) {
        
        HLNeteworkTool.shareInstance.loadStatusData(since_id, max_id: max_id) { (response, error) -> Void in
            
            if error  == nil {
                // 把字典转模型  并且保存为一个数组
                let array = response!["statuses"] as! [[String:AnyObject]]
                
                //创建一个空数组 用来保存微博模型
                var statusesData = [HLStatuses]()
                
                //遍历数组中的所有字典 转模型
                for dict in array {
                    
                    let statuse: HLStatuses = HLStatuses(dict: dict)
                    
                    statusesData.append(statuse)
                }
                // 在把模型数据传回控制器之前把图片缓存下来
                
                self.downImageCallBack(statusesData,error: error, finshesCallBack: finshesCallBack)
            } else { //没有值就自己回调
                finshesCallBack(statuses: nil, error: error)
            }
            
        }
    }
    
    
    /// 缓存图片
    func downImageCallBack(statuses:[HLStatuses],error:NSError?,finshesCallBack:(statuses:[HLStatuses]?,error:NSError?) ->()) {
        
        let group = dispatch_group_create()
        
        var length = 0
        
        // 获取模型里面的图片地址来下载
        for status in statuses {
            // 要下载的图片
            var urls: [NSURL] = [NSURL]()
            
            // 查找原创微博要下载的图片
            if let downloadURL = status.storePictureUrl {
                urls = downloadURL
            }
            
            if let downloadURL = status.retweeted_status?.storePictureUrl {
                urls = downloadURL
            }
            
            // 其实只需要缓存带一张图片的微博的这个图片
            if urls.count == 1 {
                // 只下载有一张图片的
                let url = urls.first
                
                //            for url in urls {
                // 进入组
                dispatch_group_enter(group)
                // 下载图片异步任务
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, error, _, _, _) -> Void in
                    dispatch_group_leave(group)
                    
                    if error != nil {
                        print("下载出错: \(error)")
                        return
                    }
                    
                    let data = UIImagePNGRepresentation(image)
                    length += data!.length
                })
            }
        }
        
        // 所有图片缓存完需要让控制器去显示数据
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            print("所有图片下载完成,通知控制器显示数据: 缓存图片大小: \(CGFloat(length) / 1024.0 / 1024.0) MB")
            finshesCallBack(statuses: statuses, error: nil)
        }
    }
}

        